package com.xbongbong.workflow.impl;

import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasAppEntity;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.domain.entity.ext.PaasProcessTemplateEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.model.PaasAppModel;
import com.xbongbong.paas.model.PaasProcessTemplateModel;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.menu.enums.SystemAppMenuEnum;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.WorkOrderFormEntity;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.workflow.UpgradeService;
import com.xbongbong.workflow.pojo.UpgradeToWorkflowDTO;
import com.xbongbong.workflow.upgrade.BusinessRuleUpgradeWorkflowHelp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2021/06/11 11:26
 */
@Service("upgradeService")
@Slf4j
public class UpgradeServiceImpl implements UpgradeService {

    @Resource
    private PaasProcessTemplateModel paasProcessTemplateModel;
    @Resource
    private BusinessRuleUpgradeWorkflowHelp businessRuleUpgradeWorkflowHelp;
    @Resource
    private ProFormHelp proFormHelp;
    @Resource
    private PaasAppModel paasAppModel;

    @Override
    public String upgradeBusinessRule(UpgradeToWorkflowDTO baseDTO) throws XbbException {
        try {
            // 获取当前公司的所有业务规则
            String corpid = baseDTO.getCorpid();

            PaasAppEntity paasAppEntity = paasAppModel.getByAlias(SystemAppMenuEnum.DISTRIBUTOR.getAlias(), corpid);
            if (Objects.nonNull(baseDTO.getType()) && Objects.equals(baseDTO.getType(), 1)) {
                if (Objects.nonNull(paasAppEntity) && Objects.equals(paasAppEntity.getEnable(), 1)) {
                    return "存在经销商管理，禁止迁移";
                }
            } else {
                if (Objects.nonNull(paasAppEntity)) {
                    return "存在经销商管理，禁止迁移";
                }
            }
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            // 获取流程模板，并且拿到有流程的业务规则
            param.put(StringConstant.CORPID, corpid);
            param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
            if (Objects.nonNull(baseDTO.getFormId())) {
                param.put(StringConstant.FORM_ID, baseDTO.getFormId());
            }
            param.put(StringConstant.BUSINESS_TYPE, baseDTO.getBusinessType());
            List<PaasProcessTemplateEntityExt> templateList = paasProcessTemplateModel.list(param);
            Map<Long, Integer> hasProcessFormId = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long, Integer> hasProcessWorkOrderFormId = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            List<Long> formIdList = new ArrayList<>();
            List<Long> workOrderFormIdList = new ArrayList<>();
            templateList.forEach(item->{
                if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), item.getBusinessType())) {
                    hasProcessWorkOrderFormId.put(item.getFormId(), item.getBusinessType());
                    workOrderFormIdList.add(item.getFormId());
                } else {
                    hasProcessFormId.put(item.getFormId(), item.getBusinessType());
                    formIdList.add(item.getFormId());
                }
            });
            Map<Long, PaasFormEntity> formMap = proFormHelp.getFormMap(formIdList, corpid, DelEnum.NORMAL.getDel());
            Map<Long, WorkOrderFormEntity> workOrderFormMap = proFormHelp.getWorkOrderFormMap(workOrderFormIdList, corpid, DelEnum.NORMAL.getDel());
            // 非工单
            log.warn("非工单模板迁移开始");
            businessRuleUpgradeWorkflowHelp.processUpgradeBusinessRule(hasProcessFormId, baseDTO, formMap, workOrderFormMap);
            log.warn("非工单模板迁移结束");
            log.warn("工单模板迁移开始");
            // 工单
            businessRuleUpgradeWorkflowHelp.processUpgradeBusinessRule(hasProcessWorkOrderFormId, baseDTO, formMap, workOrderFormMap);
            log.warn("工单模板迁移结束");

            return "success";
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            log.error("com.xbongbong.workflow.impl.UpgradeServiceImpl.upgradeBusinessRule error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    private static void removeProcessFormId(Map<Long, Integer> hasProcessFormId, Map<Long, Integer> formId ) {
        // 去除含有流程的业务规则，留下无流程的业务规则表单
        if (Objects.isNull(hasProcessFormId) || hasProcessFormId.isEmpty()) {
            return;
        }
        formId.keySet().removeIf(entry-> hasProcessFormId.containsKey(entry));
    }
}
